<?php

namespace App\Http\Controllers\Api;

use App\Models\Article;
use App\Models\ArticleCount;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    //文章列表分页
    public function index(Request $request){
        $data=Article::select(['id','pic','title','desn','updated_at'])->paginate(config('app.pagesize'));
        return ['code'=>0,'msg'=>'成功','data'=>$data];
    }
    //文章详情
    public function show(Article $article){
        return ['code' => 0, 'msg' => '成功', 'data' => $article];
    }
    //文章访问统计
    public function count(Request $request){
        //获取文章id
        $art_id = $request->get('art_id');
        //访问者id
        $rent_id=$request->get('rid');
        //当天日期
        $vdt=date('Y-m-d');
        //文章表访问量自增
        Article::where('id',$art_id)->increment('click',1);
        //统计表  当前文章对应当前用户在当天是否有记录，有则访问量自增，没有则新增
        $ret=ArticleCount::where('rid',$rent_id)->where('art_id',$art_id)->where('vdt',$vdt)->first();
        if(!$ret){
            //么有记录
            $ret=ArticleCount::create(['rid'=>$rent_id,'art_id'=>$art_id,'vdt'=>$vdt,'click'=>1]);
        }else{
            //自增
            $ret->increment('click');
        }
        return ['code'=>0,'msg'=>'成功','data'=>$ret->click];
    }
}
